package cc.devclub.ftd.thread.lifecycle;

/**
 * @ClassName MyThreadState
 * @Description TODO
 * @Author Huchao
 * @Date 2021/11/9 16:19
 * @Version 1.0
 **/
// 观察线程的状态
public class MyThreadState {
    public static void main(String[] args) throws InterruptedException {

        // 线程定义
        Thread thread = new Thread(() -> {
            System.out.println("线程开始运行");
            for (int i = 0; i < 5; i++) {
                System.out.println("线程运行中：" + i);
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
            System.out.println("线程运行结束");
        });

        // 线程新建(NEW)状态
        Thread.State state = thread.getState();
        System.out.println("线程状态为:" + state);

        // 线程启动后变为(RUNNABLE)状态
        thread.start();
        state = thread.getState();
        System.out.println("线程状态为:" + state);

        // 只要线程未运行结束，就一直输出线程当前的状态
        while (state != Thread.State.TERMINATED) {
//            Thread.sleep(100);
            state = thread.getState();
            // 观察当前线程状态
            System.out.println("线程状态为:" + state);
        }
    }

}
